/*
PearReview - The peer review assistant.
Copyright (C) 2009  Dimitrij Pankratz, Anton Musichin
http://www.pearreview.com, info@pearreview.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

package com.pearreview.ui;

import java.awt.Color;
import java.awt.Font;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.border.Border;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;

public class DateSpinner extends JSpinner {
	
	private static final long serialVersionUID = 4616051997190167477L;

	public DateSpinner() {
		super(new SpinnerDateModel());
		setFont(new Font("Tahoma", Font.PLAIN, 12));
		
		DateEditor editor = new LocaleDateEditor(this, Locale.getDefault());
		
		JFormattedTextField tf = editor.getTextField();
		CutCopyPasteManager.getInstance().registerJTextComponent(tf);
		FadingManager.getInstance().registerComponent(tf);
		setEditor(editor);
		tf.setHorizontalAlignment(JFormattedTextField.LEFT);
		
		Border border = BorderFactory.createMatteBorder(
				1, 1, 1, 1, new Color(0x828790));
		if (System.getProperty("os.name").equals("Mac OS X")) {
			tf.setBorder(border);
		} else {
			setBorder(border);
		}
	}
	
	public void setDate(Date date) {
		SpinnerDateModel model = (SpinnerDateModel)getModel();
		model.setValue(date);
	}
	
	public Date getDate() {
		SpinnerDateModel model = (SpinnerDateModel)getModel();
		return model.getDate();
	}
	
	public class LocaleDateEditor extends JSpinner.DateEditor {
		private static final long serialVersionUID = -5112006583103113382L;
		private Locale locale;
		public LocaleDateEditor(JSpinner spinner, Locale locale) {
			super(spinner);
			this.locale = locale;
			
			initialize();
		}
		
		private void initialize() {
			DateFormat format = DateFormat.getDateInstance(
					DateFormat.DEFAULT, getLocale());
			
			DateFormatter df = new DateFormatter(format);
			
			DefaultFormatterFactory dff = new DefaultFormatterFactory(df);
			
			getTextField().setFormatterFactory(dff);
		}
		
		public Locale getLocale() {
			return locale;
		}
	}
}
